﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace QD.DataBase.Connection
{
    public class DbConnection
    {

        public string ConnectionString { get; private set; }

        public static IDictionary<String, DbConnection> Items { get { return _store; } set { _store = value; } }

        static IDictionary<String, DbConnection> _store = new Dictionary<String, DbConnection>(StringComparer.OrdinalIgnoreCase);

        public DbConnection(mConnection model)
        {
            Init(model);
        }

        private void Init(mConnection model)
        {
            switch (model.DBType)
            {
                case DataBaseType.MSSql:
                    ConnectionString = String.Format("Data Source={0};Initial Catalog={1};User ID={2};pwd={3};", model.Host, model.DbName, model.UserName, model.Password);
                    break;
                case DataBaseType.MySql:
                    ConnectionString = String.Format("SERVER={0};DATABASE={1};USER={2};PASSWORD={3};", model.Host, model.DbName, model.UserName, model.Password);
                    break;
            }
        }

        public static String GetConnectionString(mConnection model)
        {
            return new DbConnection(model).ConnectionString;
        }

        private static DbConnection _default = null;

        public static DbConnection Default
        {
            get
            {
                if (_default == null)
                {
                    mConnection model = new mConnection();
                    model.DbName = ConfigurationManager.AppSettings["DbSetting.DB"];
                    model.UserName = ConfigurationManager.AppSettings["DbSetting.User"];
                    model.Password = ConfigurationManager.AppSettings["DbSetting.Password"];
                    model.Host = ConfigurationManager.AppSettings["DbSetting.Source"];
                    string type = ConfigurationManager.AppSettings["DbSetting.DbType"];
                    if (type == "mysql")
                        model.DBType = DataBaseType.MySql;
                    else if (type == "mssql")
                        model.DBType = DataBaseType.MSSql;
                    _default = new DbConnection(model);
                }
                return _default;
            }
            set { _default = value; }
        }

    }
}
